from html.parser import HTMLParser
import os
class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.f=[0]
        self.idnum=0
    def handle_starttag(self, tag, attrs):
        """
        recognize start tag, like <div>
        :param tag:
        :param attrs:
        :return:
        """
        self.idnum=self.idnum+1
        sid=self.idnum
        self.f.append(sid)
        print("Encountered a start tag:%s fid:%d sid:%d"%(tag,self.f[-2],sid))

    def handle_endtag(self, tag):
        """
        recognize end tag, like </div>
        :param tag:
        :return:
        """
        self.f.pop(-1)
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        """
        recognize data, html content string
        :param data:
        :return:
        """
        print("Encountered some data  :", data)

    def handle_startendtag(self, tag, attrs):
        """
        recognize tag that without endtag, like <img />
        :param tag:
        :param attrs:
        :return:
        """
        self.idnum=self.idnum+1
        sid=self.idnum
        print("Encountered startendtag :%s fid:%d sid:%d"%(tag,self.f[-1],sid))

    def handle_comment(self,data):
        """

        :param data:
        :return:
        """
        print("Encountered comment :", data)
        
def _attr(attrlist, attrname):
    for attr in attrlist:
        if attr[0] == attrname:
            return attr[1]
    return None

parser = MyHTMLParser()
f=open("htmlparserTest.html","r")
html=f.read()
print(html)
parser.feed(html)
